//index.js
//获取应用实例
const app = getApp()
var indexData = require("../indexdata/indexdata.js");
const util = require('../../utils/util.js')
var num = 0;
var sortRule1 = true; // 价格
var sortRule2 = true; // 销量
var sortClick1 = 2;
var sortClick2 = 2;
var twoBtn = false; //单列多列
Page({
  data: {
    listbzdw: "",
    currentTab: 0,
    winHeight: 0,
    winWidth: 0,
    bannerImg: [ //轮播图片
      app.globalData.url + "TsdXcx/img/banner/" + app.globalData.comid + "/" + app.globalData.nzid + "banner1.jpg",
      app.globalData.url + "TsdXcx/img/banner/" + app.globalData.comid + "/" + app.globalData.nzid + "banner2.jpg",
      app.globalData.url + "TsdXcx/img/banner/" + app.globalData.comid + "/" + app.globalData.nzid + "banner3.jpg"
    ],
    classif: [ //分类
      {
        "img": "../images/inviteHome/all.png",
        "flxh": 0,
        "text": "全部"
      },
      {
        "img": "../images/inviteHome/dancigou.png",
        "flxh": 1,
        "text": "单日购买"
      },
      {
        "img": "../images/inviteHome/xinxianshucai.png",
        "flxh": 2,
        "text": "新鲜蔬菜"
      },
      {
        "img": "../images/inviteHome/shilingshuiguo.png",
        "flxh": 3,
        "text": "时令水果"
      },
      {
        "img": "../images/inviteHome/shuichendongpin.png",
        "flxh": 4,
        "text": "水产冻品"
      },
      {
        "img": "../images/inviteHome/rouqin.png",
        "flxh": 5,
        "text": "肉禽蛋品"
      },
      {
        "img": "../images/inviteHome/liangyoutiaowen.png",
        "flxh": 6,
        "text": "粮油调味"
      },
      {
        "img": "../images/inviteHome/xiuxianshipin.png",
        "flxh": 7,
        "text": "休闲食品"
      },
      {
        "img": "../images/inviteHome/jvjiabaihuo.png",
        "flxh": 8,
        "text": "居家百货"
      },
      {
        "img": "../images/inviteHome/shenghuofuwu.png",
        "flxh": 9,
        "text": "生活服务"
      },

    ],
    flashSalebg: {
      "flashSalebg1": "http://www.tianshangding.cn/font/img/countDownR1.png",
      "flashSalebg2": "http://www.tianshangding.cn/font/img/countDownR2.png",
      "flashSalebg3": "http://www.tianshangding.cn/font/img/countDownR3.png"
    },
    sortClick1: 1,
    sortClick2: 1,
    twoBtn: false,
    sortImg: {
      "sort1": "../images/index/sort1.png",
      "sort2": "../images/index/sort2.png",
      "sort3": "../images/index/sort3.png",
      "two": "../images/index/two.png", //两列
      "one": "../images/index/one.png" //单行
    },
    usedata: "", //产品列表信息
    usedata2: "", //产品列表信息
    shopSumText: "",
    timer: "", //定时器
    countDownTime: { // 倒计时
      "dianImg": "../images/index/dian.png", //时间点
      "startTime": "November 10,2019 23:59:50", //开始日期
      "endTime": "November 11,2019 00:00:00", //结束日期
      "hour": "00", //时
      "minute": "00", //分
      "second": "10" //秒
    },
    navbarInitTop: 0, //导航栏初始化距顶部的距离
    isFixedTop: false, //是否固定顶部
    flag: false,
    shoppingNumber: '3',
    newsid: null,
    productImg: null,
    syspars: "",
    classIfIdTop: 0,//20200221配送到家
    elasticFrameImg: "../images/index/tankuang.png",//20200312弹框图
    elasticFrameBtn:false,
    //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    // canIUse: wx.canIUse('button.open-type.getUserInfo'),
    // isHide: false,
    purchase:'',//20200428
    purchaseIndex:0,
    cashCouponLq:'',
    cashCouponLqBtn:true,
    cashCouponLqBtnText: true,
    cashCouponCRText:"立即领取",
    customerBtn: false,
    kefuBtn:true,
    liuyanBtn:true,
    customerNumber:2,
    liuyanSuccess:true,
    textareaCustomer:true,
    textareaText:'',
    tabBar: indexData.tabBar,//tabar
  },
  onLoad: function () {
    var that = this;
    that.setData({
      purchase: indexData.purchase,//20200428
      usedata: indexData.setdata,//20200428
      purchase: indexData.purchase,
      cashCouponLq: indexData.cashCouponLq,
      tabBar: indexData.tabBar,
    })
    wx.request({
      url: app.globalData.ApiUrl + 'GetMilkLeixing',
      data: {
        nzid: app.globalData.nzid
      },
      header: {
        //'content-type': 'application/jsonp;charset=utf-8'
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      method: 'GET',
      dataType: 'json',
      success: function (res) {
        //console.log(res.data);
        // that.setData({
        //   classif: res.data
        // })
      },
      fail: function (err) {
        console.log("requrest fail:" + err)
      }
    })
    wx.request({
      url: app.globalData.ApiUrl + 'GetOnlineSp4',
      data: {
        nzid: app.globalData.nzid
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      method: 'GET',
      dataType: 'json',
      success: function (res) {
        console.log(res.data);
        that.setData({
          // usedata: res.data,
          winHeight: res.data[0].maxflsl * 110
        })
      }
    })

    this.setData({
      // listbzdw: util.bzdw_caption,
      messageRolling: indexData.messageRolling
    })
    wx.setTabBarBadge({ //购物车数量
      index: 1,
      text: this.data.shoppingNumber,
      color: "black"
    })
    var page = this;
    wx.getSystemInfo({
      success: function (res) {

        page.setData({
          //winHeight: res.windowHeight,
          winWidth: res.windowWidth
        });

      },
    })
    wx.showShareMenu({
      withShareTicket: true
    });
    wx.hideTabBar();//tabBar隐藏


  //   // 查看是否授权
  //   wx.getSetting({
  //     success: function (res) {
  //       if (res.authSetting['scope.userInfo']) {
  //         wx.getUserInfo({
  //           success: function (res) {
  //             // 用户已经授权过,不需要显示授权页面,所以不需要改变 isHide 的值
  //             // 根据自己的需求有其他操作再补充
  //             // 我这里实现的是在用户授权成功后，调用微信的 wx.login 接口，从而获取code
  //             wx.login({
  //               success: res => {
  //                 // 获取到用户的 code 之后：res.code
  //                 console.log("用户的code:" + res.code);
  //                 // 可以传给后台，再经过解析获取用户的 openid
  //                 // 或者可以直接使用微信的提供的接口直接获取 openid ，方法如下：
  //                 // wx.request({
  //                 //     // 自行补上自己的 APPID 和 SECRET
  //                 //     url: 'https://api.weixin.qq.com/sns/jscode2session?appid=自己的APPID&secret=自己的SECRET&js_code=' + res.code + '&grant_type=authorization_code',
  //                 //     success: res => {
  //                 //         // 获取到用户的 openid
  //                 //         console.log("用户的openid:" + res.data.openid);
  //                 //     }
  //                 // });
  //               }
  //             });
  //           }
  //         });
  //       } else {
  //         // 用户没有授权
  //         // 改变 isHide 的值，显示授权页面
  //         that.setData({
  //           isHide: true
  //         });
  //       }
  //     }
  //   });
  // },

  // bindGetUserInfo: function (e) {
  //   if (e.detail.userInfo) {
  //     //用户按了允许授权按钮
  //     var that = this;
  //     // 获取到用户的信息了，打印到控制台上看下
  //     console.log("用户的信息如下：");
  //     console.log(e.detail.userInfo);
  //     //授权成功后,通过改变 isHide 的值，让实现页面显示出来，把授权页面隐藏起来
  //     that.setData({
  //       isHide: false
  //     });
  //   } else {
  //     //用户按了拒绝按钮
  //     wx.showModal({
  //       title: '警告',
  //       content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
  //       showCancel: false,
  //       confirmText: '返回授权',
  //       success: function (res) {
  //         // 用户没有授权成功，不需要改变 isHide 的值
  //         if (res.confirm) {
  //           console.log('用户点击了“返回授权”');
  //         }
  //       }
  //     });
  //   }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // tabar选中状态
    var tabBar = this.data.tabBar;
    tabBar[0].select = false;
    tabBar[1].select = true;
    tabBar[2].select = false;
    tabBar[3].select = false;
    this.setData({
      tabBar: tabBar
    })
  },

  // 页面渲染 调用
  onShow: function () {
    // new Date('2017-06-06 15:31:09').getTime()
    this.countDown();
    var that = this;

    if (that.data.navbarInitTop == 0) {
      //获取节点距离顶部的距离
      wx.createSelectorQuery().select('#navbar').boundingClientRect(function (rect) {
        if (rect && rect.top > 0) {
          var navbarInitTop = parseInt(rect.top);
          that.setData({
            navbarInitTop: navbarInitTop
          });
        }
      }).exec();
    }
    // 20200221分类
    if (that.data.classIfIdTop == 0) {
      //获取节点距离顶部的距离
      wx.createSelectorQuery().select('#classIfIdTop').boundingClientRect(function (rect) {
        if (rect && rect.top > 0) {
          var classIfIdTop = parseInt(rect.top);
          that.setData({
            classIfIdTop: classIfIdTop
          });
        }
      }).exec();
    }

  },
  /**
   * 监听页面滑动事件
   */
  onPageScroll: function (e) {
    var that = this;
    var scrollTop = parseInt(e.scrollTop); //滚动条距离顶部高度
    //判断'滚动条'滚动的距离 和 '元素在初始时'距顶部的距离进行判断
    var isSatisfy = scrollTop >= that.data.navbarInitTop ? true : false;
    //为了防止不停的setData, 这儿做了一个等式判断。 只有处于吸顶的临界值才会不相等
    if (that.data.isFixedTop === isSatisfy) {
      return false;
    }
    that.setData({
      isFixedTop: isSatisfy,
      flag: isSatisfy
    });
  },
  countDown: function () { //倒计时
    let that = this;
    var startTime = new Date(this.data.countDownTime.startTime).getTime();
    var endTime = new Date(this.data.countDownTime.endTime).getTime();
    var totalSecond = (endTime - startTime) / 1000;
    var t = totalSecond;
    that.setData({
      timer: setInterval(function () {
        t--;
        if (t > 0) {
          that.setData({
            hour: addzero(Math.floor(t / 3600)),
            minute: addzero(Math.floor(t % 3600 / 60)),
            second: addzero(Math.floor(t % 60))
          })
        } else {
          that.setData({
            hour: "00",
            minute: "00",
            second: "00"
          })
          clearInterval(that.data.timer);
        }
      }, 1000)

    })

    function addzero(n) {
      if (n < 10) {
        return '0' + n
      } else {
        return '' + n
      }
    }
  },
  shopBtn: function () {
    // 购物车添加
    num++;
    this.setData({
      shopSumText: num
    })
    app.globalData.ee = num;
  },
  mySort1: function (e) {
    // 价格
    //property 根据什么排序
    var property = e.currentTarget.dataset.property;
    var self = this;
    var arr = self.data.usedata;
    sortRule2 = true;
    sortClick2 = 1;
    this.setData({
      sortClick2: sortClick2
    })
    sortClick2 = 2;
    if (sortClick1 == 1) {
      sortRule1 = true;
      self.setData({
        usedata: arr.sort(self.compare(property, sortRule1))
      });
      sortRule1 = true;
    } else if (sortClick1 == 2) {
      sortRule1 = true;
      self.setData({
        usedata: arr.sort(self.compare(property, sortRule1))
      });
    } else if (sortClick1 == 3) {
      sortRule1 = false;
      self.setData({
        usedata: arr.sort(self.compare(property, sortRule1))
      });
    }
    this.setData({
      sortClick1: sortClick1
    })
    console.log(sortClick1)
    sortClick1++;
    if (sortClick1 > 3) {
      sortClick1 = 1;
    }
    // 点击排序
    var that = this;
    var isFixedTop = that.data.isFixedTop; //isFixedTop是一个开关变量，用来控制点击滑动到指定位置
    var query = wx.createSelectorQuery(); //获取某个元素返回的是一个对象
    if (isFixedTop) {
      var _heightd = this.data.navbarInitTop;
      wx.pageScrollTo({
        scrollTop: _heightd, //页面滚动的距离
        duration: 300, //页面滚动速度 单位ms
        success: function (e) { //成功函数
          that.setData({
            flag: false
          })
        }
      });
    }
  },
  mySort2: function (e) {
    // 销量
    //property 根据什么排序
    var property = e.currentTarget.dataset.property;
    var self = this;
    var arr = self.data.usedata;
    sortRule1 = true;
    sortClick1 = 1;
    this.setData({
      sortClick1: sortClick1
    })
    sortClick1 = 2;
    if (sortClick2 == 1) {
      sortRule2 = true;
      self.setData({
        usedata: arr.sort(self.compare(property, sortRule2))
      });
      sortRule2 = true;
    } else if (sortClick2 == 2) {
      sortRule2 = false;
      self.setData({
        usedata: arr.sort(self.compare(property, sortRule2))
      });
    } else if (sortClick2 == 3) {
      sortRule2 = true;
      self.setData({
        usedata: arr.sort(self.compare(property, sortRule2))
      });
    }
    this.setData({
      sortClick2: sortClick2
    })
    sortClick2++;
    if (sortClick2 > 3) {
      sortClick2 = 1;
    }
    console.log(sortClick2)
    // 点击排序
    var that = this;
    var isFixedTop = that.data.isFixedTop; //isFixedTop是一个开关变量，用来控制点击滑动到指定位置
    var query = wx.createSelectorQuery(); //获取某个元素返回的是一个对象
    if (isFixedTop) {
      var _heightd = this.data.navbarInitTop;
      wx.pageScrollTo({
        scrollTop: _heightd, //页面滚动的距离
        duration: 300, //页面滚动速度 单位ms
        success: function (e) { //成功函数
          that.setData({
            flag: false
          })
        }
      });
    }

  },
  compare: function (property, bol) {
    // 排序计算
    return function (a, b) {
      var value1 = a[property];
      var value2 = b[property];
      if (bol) {
        return value1 - value2;
      } else {
        return value2 - value1;
      }
    }

  },
  twoBtn: function () {
    twoBtn = !twoBtn;
    this.setData({
      twoBtn: twoBtn
    })
  },
  goClassif: function (event) {
    var page = this;
    if (this.data.currentTab == event.target.dataset.current) {
      return false;
    } else {
      page.setData({
        currentTab: event.target.dataset.current
      });
    }
  },
  goDetails: function (event) {
    var that = this;
    var syspars = null;
    wx.request({
      url: app.globalData.ApiUrl + 'GetDinggouSetting2',
      data: {
        nzid: app.globalData.nzid,
        spid: event.currentTarget.dataset.newsid
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8"
      },
      method: 'GET',
      dataType: 'json',
      success: function (res) {
        that.setData({
          syspars: res.data,
        })

        //event.currentTarget.dataset 中的大写字母会自动转为小写
        // var productImg = event.currentTarget.dataset.productimg
        var sp = event.currentTarget.dataset.sp;
        var len = that.data.usedata.length
        var tjsp = [sp]
        var k = 0
        for (var i = 0; i < len; i++) {
          if (sp.flxh == that.data.usedata[i].flxh && sp.spid != that.data.usedata[i].spid && sp.bzdw == that.data.usedata[i].bzdw) {
            if (k < 3) {
              tjsp.push(that.data.usedata[i])
              k++
            }
          }
        }
        var spinfo = {
          syspars: that.data.syspars,
          sp: sp,
          tjsp: tjsp,
          bzdw: sp.bzdw,
          stock: 1000000,
          num: 1, //每天数量
          price: sp.price,
          priceSum: sp.price, //每天金额
          priceSumday: util.dnTs[0].milkingDay * sp.price, //合计金额
        }
        //console.log(event);
        wx.navigateTo({
          //url: '../details/details?newsid=' + newsid + '&productImg=' + productImg+'&spmc='+spmc
          url: '../details/details?spinfo=' + JSON.stringify(spinfo)
          // 跳转到商品详情
        })
      }
    })

  },
  goRegion: function () {
    wx.navigateTo({
      url: '../areaThree/areaThree'
      // 20200211跳转到地区选择
    })
  },
  onShareAppMessage: function (res) {//20200313转发
    return {
      title: '自定义',
      path: '这里写你这个页面的路径',
      imageUrl: '../images/index/tankuang.png',
      success: function (shareTickets) {
        console.info(shareTickets + '成功');
        // 转发成功
      },
      fail: function (res) {
        console.log(res + '失败');
        // 转发失败
      },
      complete: function (res) {
        // 不管成功失败都会执行
      }
    }
  },
  switchTab(event) { //20200219分类左右滑动切换
    var cur = event.detail.current;
    var singleNavWidth = this.data.windowWidth / (this.data.classif.lenght);
    this.setData({
      currentTab: cur,
      navScrollLeft: (cur - 2) * singleNavWidth
    });
  },
  //20200221配送到家
  goTop: function () {
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: this.data.classIfIdTop
      })
    }
  },
  goDefaultHead: function () {//20200224跳到社团
    wx.navigateTo({
      url: '/inviteHome/pages/defaultHead/defaultHead'
    })
  },
  //弹框图显示，tabBar显示
  elasticFrameHide: function () {
    var elasticFrameBtn = this.data.elasticFrameBtn;
    elasticFrameBtn = true;
    this.setData({
      elasticFrameBtn: elasticFrameBtn
    })
    wx.showTabBar();//显示tabBar
  },
    goIndexFenLei: function (event) {
    var newsid = event.currentTarget.dataset.newsid;
    wx.navigateTo({
      // url: '../indexDetails/indexDetails?newsid=' + newsid
      url: '../indexDetail/indexDetail?newsid=' + newsid
      // 跳转到商品分类
    })
  },
  add: function (e) {
    // 加
    var count = this.data.usedata;
    var index = e.currentTarget.dataset.index;
    count[index].countNum++;
    count[index].minusBtn = false;
    this.setData({
      usedata: count
    });

    // this.countSum()
  },
  minus: function (e) {
    // 减
    var count = this.data.usedata;
    var index = e.currentTarget.dataset.index;
    if (count[index].countNum <= 1) {
      count[index].countNum = 0;
      count[index].minusBtn = true;
    } else {
      count[index].countNum--;
      count[index].minusBtn = false;
    }
    this.setData({
      usedata: count
    })
    // this.countSum()
  },
  goClassifSellers: function (event) {
    var page = this;
    console.log(event.currentTarget.dataset.current)
    if (page.data.currentTab == event.currentTarget.dataset.current) {
      return false;
    } else {
      page.setData({
        currentTab: event.currentTarget.dataset.current
      });
    }
  },
  goPurchase: function (event) {
    var page = this;
    console.log(event.currentTarget.dataset.current)
    if (page.data.purchaseIndex == event.currentTarget.dataset.current) {
      return false;
    } else {
      page.setData({
        purchaseIndex: event.currentTarget.dataset.current
      });
    }
    if (event.currentTarget.dataset.current==2){

      this.goDefaultHead();
      setTimeout(function () {
        page.setData({
          purchaseIndex: 0
        });
      }, 1000)

    }
    
  },
  goIndexDetails: function (event) {
    var newsid = event.currentTarget.dataset.newsid;
    wx.navigateTo({
      url: '../details/details?newsid=' + newsid
      // 跳转到商品详情
    })
  },//领悟优惠券
  couponLqBtnShow: function () {
    if (this.data.cashCouponLqBtnText){
      wx.showToast({
        title: '领取成功',
        icon: 'success',
        duration: 500
      })
    }

    this.setData({
      cashCouponLqBtn: false,
      cashCouponLqBtnText:false,
      cashCouponCRText:"已领取"
    })
  },
  cashCouponLqAllHide: function () {
    this.setData({
      cashCouponLqBtn:true
    })
  },
  //点击弹出
  customerBtn: function () {
    var customerBtn = !this.data.customerBtn
      this.setData({
        customerBtn: customerBtn
      })
  },
  kefuBtn: function () {
    
    var kefuBtn = !this.data.kefuBtn
    this.setData({
      kefuBtn: kefuBtn,
      customerBtn: false
    })
  },
  liuyanBtn: function () {
    var liuyanBtn = !this.data.liuyanBtn
    this.setData({
      liuyanBtn: liuyanBtn,
      customerBtn: false,
      textareaText: '',
      textareaCustomer: true,
    })
  },
  customerBtnHide: function () {
    this.setData({
      kefuBtn: true,
      liuyanBtn: true
    })
  }, 
  customerBtnSuccess: function () {
    this.setData({
      kefuBtn: true,
      liuyanBtn: true,
      liuyanSuccess: false,
      
    });
    this.customerDown()
    
  },  
  customerBtnSuccessHide: function () {
    this.setData({
      liuyanSuccess: true
    });
  },
  customerDown() { //倒计时函数
  var that=this
    var customerDown=setInterval(function(){
      var customerNumber = that.data.customerNumber;
      console.log(customerNumber)
      if (customerNumber <=1) {
        that.setData({
          liuyanSuccess: true,
          customerNumber:2,
          
        })
        clearInterval(customerDown);
      } else {
        customerNumber--;
      }
      that.setData({
        customerNumber: customerNumber,
      })
    }, 1000);

  },
  textareaCustomer(e) {//吐槽
    this.data.textareaCustomer = e.detail.value.replace(/\s+/g, '');
    this.setData({
      textareaText: this.data.textareaCustomer
    });
    this.customerText()
  },
  customerText: function () {
    if (this.data.textareaCustomer) {
      this.setData({
        textareaCustomer: false,
        customerNumber: 2
      });
    } else {
      this.setData({
        textareaCustomer: true,
      });
    }
  },
  goTabBar: function (event) {
    var newsid = event.currentTarget.dataset.newsid;
    wx.redirectTo({
      url: newsid
      // 跳转tabBar
    })
  },    
})